import { Request, Response } from 'express';
import { classifyService } from '../services/classifyService';
import { CreateClassifyRequest, UpdateClassifyRequest } from '../types/classify';
import { ApiResponse, HttpStatus } from '../types/api';
import { validationResult } from 'express-validator';

/**
 * 分类控制器类
 * 处理分类相关的HTTP请求
 */
export class ClassifyController {
  /**
   * 获取所有分类（支持分页和搜索）
   * GET /api/classifies
   */
  async getAllClassifies(req: Request, res: Response): Promise<void> {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;
      const search = req.query.search as string;
      const sortBy = req.query.sortBy as string || 'createdAt';
      const sortOrder = req.query.sortOrder as string || 'desc';

      const result = await classifyService.getAllClassifies({
        page,
        limit,
        search,
        sortBy,
        sortOrder
      });

      const response: ApiResponse = {
        success: true,
        data: result.classifies,
        pagination: {
          page: result.page,
          limit: result.limit,
          total: result.total,
          totalPages: result.totalPages
        },
        message: '获取分类列表成功'
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `获取分类列表失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 根据ID获取单个分类
   * GET /api/classifies/:id
   */
  async getClassifyById(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const classify = await classifyService.getClassifyById(id);

      if (!classify) {
        const response: ApiResponse = {
          success: false,
          error: '分类不存在'
        };
        res.status(HttpStatus.NOT_FOUND).json(response);
        return;
      }

      const response: ApiResponse = {
        success: true,
        data: classify,
        message: '获取分类成功'
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `获取分类失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 创建新分类
   * POST /api/classifies
   */
  async createClassify(req: Request, res: Response): Promise<void> {
    try {
      // 检查验证错误
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        const response: ApiResponse = {
          success: false,
          error: '输入数据验证失败',
          errors: errors.array().map((err: any) => ({
            field: err.path,
            message: err.msg
          }))
        };
        res.status(HttpStatus.BAD_REQUEST).json(response);
        return;
      }

      const classifyData: CreateClassifyRequest = req.body;
      
      // 检查分类名是否已存在
      const existingClassify = await classifyService.getClassifyByName(classifyData.name);
      if (existingClassify) {
        const response: ApiResponse = {
          success: false,
          error: '分类名已存在'
        };
        res.status(HttpStatus.CONFLICT).json(response);
        return;
      }

      const newClassify = await classifyService.createClassify(classifyData);

      const response: ApiResponse = {
        success: true,
        data: newClassify,
        message: '创建分类成功'
      };

      res.status(HttpStatus.CREATED).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `创建分类失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 更新分类
   * PUT /api/classifies/:id
   */
  async updateClassify(req: Request, res: Response): Promise<void> {
    try {
      // 检查验证错误
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        const response: ApiResponse = {
          success: false,
          error: '输入数据验证失败',
          errors: errors.array().map((err: any) => ({
            field: err.path,
            message: err.msg
          }))
        };
        res.status(HttpStatus.BAD_REQUEST).json(response);
        return;
      }

      const { id } = req.params;
      const updateData: UpdateClassifyRequest = req.body;

      // 检查分类是否存在
      const existingClassify = await classifyService.getClassifyById(id);
      if (!existingClassify) {
        const response: ApiResponse = {
          success: false,
          error: '分类不存在'
        };
        res.status(HttpStatus.NOT_FOUND).json(response);
        return;
      }

      // 如果更新名称，检查新名称是否已存在
      if (updateData.name && updateData.name !== existingClassify.name) {
        const classifyWithSameName = await classifyService.getClassifyByName(updateData.name);
        if (classifyWithSameName) {
          const response: ApiResponse = {
            success: false,
            error: '分类名已存在'
          };
          res.status(HttpStatus.CONFLICT).json(response);
          return;
        }
      }

      const updatedClassify = await classifyService.updateClassify(id, updateData);

      const response: ApiResponse = {
        success: true,
        data: updatedClassify,
        message: '更新分类成功'
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `更新分类失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 删除分类
   * DELETE /api/classifies/:id
   */
  async deleteClassify(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;

      // 检查分类是否存在
      const existingClassify = await classifyService.getClassifyById(id);
      if (!existingClassify) {
        const response: ApiResponse = {
          success: false,
          error: '分类不存在'
        };
        res.status(HttpStatus.NOT_FOUND).json(response);
        return;
      }

      await classifyService.deleteClassify(id);

      const response: ApiResponse = {
        success: true,
        message: '删除分类成功'
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `删除分类失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 批量删除分类
   * DELETE /api/classifies
   */
  async batchDeleteClassifies(req: Request, res: Response): Promise<void> {
    try {
      const { ids } = req.body;

      if (!Array.isArray(ids) || ids.length === 0) {
        const response: ApiResponse = {
          success: false,
          error: '请提供有效的分类ID数组'
        };
        res.status(HttpStatus.BAD_REQUEST).json(response);
        return;
      }

      const deletedCount = await classifyService.batchDeleteClassifies(ids);

      const response: ApiResponse = {
        success: true,
        data: { deletedCount },
        message: `成功删除 ${deletedCount} 个分类`
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `批量删除分类失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 获取分类统计信息
   * GET /api/classifies/stats
   */
  async getClassifyStats(req: Request, res: Response): Promise<void> {
    try {
      const stats = await classifyService.getClassifyStats();

      const response: ApiResponse = {
        success: true,
        data: stats,
        message: '获取分类统计信息成功'
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `获取分类统计信息失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }
}

// 导出控制器实例
export const classifyController = new ClassifyController();